code
acled<-read.csv("/Users/dave/Documents/2013/PITF/analysis/protests2021/data/2022analysis/acled2022.csv")
##Event_date variable has a "Chr" format.
#Need to convert it into date format to calculate 7 day averages for Protests and Violence against Civilians
acled$event_date<-as.Date(acled$event_date,format="%d %B %Y")
#class(acled$event_date)
##Compute number of events per day
acled$perday<-1
protests<-filter(acled,event_type=="Protests" )
stateviol<-filter(acled, event_type=="Violence against civilians")
protests<-aggregate(perday ~ event_date, data = protests, sum)
stateviol<-aggregate(perday ~ event_date, data = stateviol, sum)
##Calculating a 7 day moving average
protests$rollmean<-rollmean(protests$perday,k=7, fill=NA)
stateviol$rollmean<-rollmean(stateviol$perday,k=7, fill=NA)
protests <- protests %>% filter(protests$event_date < "2022-06-25")
stateviol <- stateviol %>% filter(stateviol$event_date < "2022-06-25")
# protestplot <- ggplot(data=protests, aes(x=event_date, y=rollmean)) +
# geom_line()+
# geom_smooth() +
# geom_vline(xintercept=as.numeric(as.Date("2020-03-15")), color="red") +
# scale_x_date(date_breaks = "6 months", date_labels = '%b %Y') +
# labs(x="Date", y="Protests", caption="7 day rolling averages; smoothed loess trend lines; red lines indicate 3.15.2020 COVID onset; 'ACLED data retrieved 7.18.22, http://acleddata.com") +
# ggtitle("Protests During the Pandemic")
#
#
# protestplot
library(highcharter)
library(dplyr)
# First handle potential NA values and ensure data is properly ordered
protests <- protests %>%
arrange(event_date) %>%
# Optionally remove NA values if present
filter(!is.na(rollmean), !is.na(event_date))
# Calculate the smoothed trend line with explicit handling of the data points
x_vals <- as.numeric(protests$event_date)
smooth_fit <- loess(rollmean ~ x_vals, data = protests, span = 0.75)
protests$smooth_trend <- predict(smooth_fit, x_vals)
bucolors<-list("#005A43","#6CC24A", "#A7DA92", "#BDBEBD", "#000000" )
# Create the highchart
hchart <- highchart() %>%
hc_add_series(
data = protests,
type = "line",
hcaes(x = event_date, y = rollmean),
color= "#000000",
name = "Rolling Average"
) %>%
hc_add_series(
data = protests,
type = "line",
hcaes(x = event_date, y = smooth_trend),
name = "Trend",
dashStyle = "Solid",
color = "#005A43",
opacity = 0.7
) %>%
hc_xAxis(
plotLines = list(list(
value = as.numeric(as.POSIXct("2020-03-15")) * 1000,
color = "red",
width = 2,
zIndex = 3
)),
type = "datetime",
dateTimeLabelFormats = list(month = "%b %Y"),
tickInterval = 6 * 30 * 24 * 3600 * 1000
) %>%
hc_yAxis(
title = list(text = "Protests")
) %>%
hc_title(
text = "Protests During the Pandemic"
) %>%
hc_caption(
text = "7 day rolling averages; smoothed loess trend lines; red line indicates 3.15.2020 COVID onset; ACLED data retrieved 7.18.22",
align = "left",
style = list(fontStyle = "italic")
) %>%
hc_tooltip(
shared = TRUE,
crosshairs = TRUE
) %>%
hc_credits(enabled = FALSE)
# Display the chart
hchart